package com.nuatar.meibi.pubvar;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import com.nuatar.meibi.MeiBi;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

public class SqlBus {
	Context context;

	public SqlBus(Context ctx) {
		context = ctx;
	}

	@SuppressLint("SdCardPath")
	public void InnitDatabase() {

		String aa = "/data/data/com.nuatar.meibi/databases/mydata.db";
		PrepareDir(aa);
		File ff = new File(aa);
		if (!ff.exists()) {
			try {
				ff.createNewFile();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			InputStream ips;
			OutputStream ops;

			try {
				ops = new FileOutputStream(aa);
				ips = context.getAssets().open("mydata.db");
				byte[] buffer = new byte[1024];

				int length = 10;

				while ((length = ips.read(buffer)) > 0) {

					ops.write(buffer, 0, length);

				}
				ops.flush();
				ops.close();
				ips.close();
			} catch (FileNotFoundException e) {

			} catch (IOException e) {

			}
		}

	}

	@SuppressLint("SdCardPath")
	public boolean hasInnited() {
		String aa = "/data/data/com.nuatar.mmku/databases/mydata.db";
		File ff = new File(aa);
		if (!ff.exists()) {
			return false;
		} else {
			return true;
		}
	}

	public void innitLocals(MeiBi mks) {
		SQLiteDatabase sd = context.openOrCreateDatabase("mydata.db",
				SQLiteDatabase.OPEN_READONLY, null);
		Cursor cc = sd.rawQuery("select * from WallPaper", null);
		while (cc.moveToNext()) {
			String id = cc.getString(cc.getColumnIndex("id"));
			String title = cc.getString(cc.getColumnIndex("title"));
			WallPaper temp = new WallPaper();
			temp.id = id;
			temp.title = title;
			String savePath = Environment.getExternalStorageDirectory()
					.getPath() + Configer.DirHead + id + "/" + id + ".des";
			File f = new File(savePath);
			if (f.exists()) {
				temp = PhoneMaster.setWallPaperImagePairs(temp);
				mks.hislist.add(temp);
			} else {
				DeleteWallPaper(temp);
				Log.e("SQLDelete", "WallPaper");
			}
		}
		cc.close();
		sd.close();
	}

	@SuppressLint("SimpleDateFormat")
	public void StoreWallPaper(WallPaper wp) {
		if (!IsExsits("WallPaper", "id", wp.id)) {
			SQLiteDatabase sd = context.openOrCreateDatabase("mydata.db",
					SQLiteDatabase.CREATE_IF_NECESSARY, null);
			ContentValues cts = new ContentValues();
			cts.put("id", wp.id);
			cts.put("title", wp.title);
			long i = sd.insert("WallPaper", null, cts);
			sd.close();
		}
	}

	public WallPaper getWallPaper(String id) {
		WallPaper wp = null;
		SQLiteDatabase sd = context.openOrCreateDatabase("mydata.db",
				SQLiteDatabase.CREATE_IF_NECESSARY, null);
		Cursor cc = sd.rawQuery(
				"select * from WallPaper where id='" + id + "'", null);
		while (cc.moveToNext()) {
			wp = new WallPaper();
			wp.id = cc.getString(cc.getColumnIndex("id"));
			wp.title = cc.getString(cc.getColumnIndex("title"));
		}
		cc.close();
		sd.close();
		return wp;
	}

	public List<WallPaper> getAllPaper() {
		List<WallPaper> list = new ArrayList<WallPaper>();

		SQLiteDatabase sd = context.openOrCreateDatabase("mydata.db",
				SQLiteDatabase.CREATE_IF_NECESSARY, null);
		Cursor cc = sd.rawQuery("select * from WallPaper", null);
		while (cc.moveToNext()) {
			WallPaper wp = null;
			wp = new WallPaper();
			wp.id = cc.getString(cc.getColumnIndex("id"));
			wp.title = cc.getString(cc.getColumnIndex("title"));
			wp.creatDate = cc.getString(cc.getColumnIndex("creatDate"));
			list.add(wp);
		}
		cc.close();
		sd.close();
		return list;
	}

	public void DeleteWallPaper(WallPaper wp) {
		SQLiteDatabase sd = context.openOrCreateDatabase("mydata.db",
				SQLiteDatabase.OPEN_READWRITE, null);
		sd.delete("WallPaper", "id=?", new String[] { wp.id });
		sd.close();
	}

	public boolean IsExsits(String table, String rowname, String rowdata) {
		SQLiteDatabase sd = context.openOrCreateDatabase("mydata.db",
				SQLiteDatabase.CREATE_IF_NECESSARY, null);
		int count = 0;
		Cursor cc = sd.rawQuery("select count(*) from " + table + " where "
				+ rowname + "='" + rowdata + "'", null);

		while (cc.moveToNext()) {
			count = Integer
					.parseInt(cc.getString(cc.getColumnIndex("count(*)")));
		}
		cc.close();
		sd.close();
		if (count == 0) {
			return false;
		} else {
			return true;
		}

	}

	public void clearFeedTable(String tabelName) {
		String sql = "DELETE FROM " + tabelName + ";";
		SQLiteDatabase db = context.openOrCreateDatabase("mydata.db",
				SQLiteDatabase.OPEN_READONLY, null);
		db.execSQL(sql);
		db.close();
		revertSeq(tabelName);

	}

	private void revertSeq(String FEED_TABLE_NAME) {
		String sql = "update sqlite_sequence set seq=0 where name='"
				+ FEED_TABLE_NAME + "'";
		SQLiteDatabase db = context.openOrCreateDatabase("mydata.db",
				SQLiteDatabase.OPEN_READONLY, null);
		db.execSQL(sql);
	}
	private static void PrepareDir(String savePath) {
		File file = new File(savePath.substring(0, savePath.lastIndexOf('/')));
		if (!file.exists()) {
			if (!file.mkdirs()) {
				Log.e("Dir", "Creat Dir lose");
			}
		}
	}

}
